<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="当事人名称" prop="companyName">
        <el-input
          v-model="queryParams.companyName"
          placeholder="请输入当事人名称"
          clearable
          :style="{ width: '220px' }"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="记录时间">
        <el-date-picker
          v-model="daterangeCreateTime"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :style="{ width: '220px' }"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb10">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['siteinspectionrecord:siteinspectionrecord:add']">
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['siteinspectionrecord:siteinspectionrecord:remove']">
          删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          :disabled="multiple"
          @click="handleExport"
          v-hasPermi="['siteinspectionrecord:siteinspectionrecord:export']">
          导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" :columns="columns" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" border :data="partyinfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <template v-for="column in newColumns" :key="column.key">
        <el-table-column
          :label="column.label"
          :prop="column.key"
          :min-width="column.minWidth || ''"
          :width="column.width || ''" />
      </template>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="240px"
        fixed="right"
        :show-overflow-tooltip="false">
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="view"
            @click="handleUpdate(scope.row, 'view')"
            v-hasPermi="['siteinspectionrecord:siteinspectionrecord:query']">
            查看
          </el-button>
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row, 'edit')"
            v-hasPermi="['siteinspectionrecord:siteinspectionrecord:edit']">
            修改
          </el-button>
          <el-button link type="primary" icon="upload" @click="handleUpload(scope.row)">上传附件</el-button>
          <el-button
            link
            type="danger"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['siteinspectionrecord:siteinspectionrecord:remove']">
            删除
          </el-button>
          <el-dropdown trigger="click" class="dropdownView" @command="handlePreview">
            <div class="el-dropdown-link" @click="handleView(scope.row)">
              <el-icon class="left-icon"><View /></el-icon>
              <span style="font-size: 14px">预览</span>
              <el-icon class="el-icon--right">
                <arrow-down />
              </el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item v-for="item in previewList" :key="item.id" :command="item.id">
                  {{ item.name }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 现场检查 -->
    <Transcript
      v-if="open"
      v-model:modalvalue="open"
      :id="formId"
      :checkBtnType="checkBtnType"
      @handleSave="handleSave" />
    <!-- 上传附件弹窗 -->
    <el-dialog title="上传附件" v-model="fileModal" width="1200px">
      <FileList v-if="fileModal" :fileUploadList="fileUploadList" />
      <template #footer>
        <div class="form-footer">
          <el-button type="primary" @click="handleUploadConfirm">保存</el-button>
          <el-button @click="() => (fileModal = false)">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Partyinfo">
import { useRoute } from 'vue-router'
import { listPartyinfo, delPartyinfo } from '@/api/partyinfo/index'
import {
  getDataList,
  onSiteInspectionDel,
  onSiteInspectionDetail,
  onSiteInspectionUpload,
  onSiteInspectionExport,
} from '@/api/onSiteInspection/index.js'
import { onSiteInspectionPreviewList, onSiteInspectionPreview } from '@/api/system/file.js'
// import detail from './detail.vue'
import Transcript from '@/views/workbench/filingReview/register/transcript.vue'
import FileUpload from '@/components/FileUpload/index.vue'
import FileList from '@/components/FileList/index.vue'
import { ElMessage } from 'element-plus'
import { downloadBlob } from '@/utils/download.js'

const { proxy } = getCurrentInstance()
const route = useRoute()

const query = route.query || {}
if (query.formId) {
  nextTick(() => {
    // 案件检索详情跳转过来
    handleUpdate({ id: query.formId }, 'view')
  })
}

const partyinfoList = ref([])
const open = ref(false)
// 现场检查详情数据
// const formData = ref({
//   field16: '0', // 是否现场检查 0否 1是
//   field21: '0', // 是否上传附件 0否 1是
//   checkDate: [], // 检查时间
//   beginCreateTime: undefined, // 检查开始时间
//   endCreateTime: undefined, // 检查结束时间
//   ttsiteInspectionRecordPhotosList: [
//     {
//       groupName: '现场检查照片',
//       photos: '',
//       evidenceTarget: undefined,
//       photoTime: undefined,
//       photoLocation: {},
//     },
//   ],
// })
const checkBtnType = ref('view') // view 查看 edit 编辑
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const formId = ref('')
const title = ref('')
const daterangeCreateTime = ref([])

const columns = ref([
  { key: 'inspectionTime', label: '检查时间', visible: true, minWidth: '150' },
  { key: 'location', label: '检查地点', visible: true, minWidth: '140' },
  { key: 'companyName', label: '当事人名称', visible: true, minWidth: '130' },
  { key: 'sitePrincipalName', label: '现场负责人', visible: true, minWidth: '100' },
  { key: 'createTime', label: '记录时间', visible: true, width: '160' },
])
const newColumns = computed(() => {
  return columns.value.filter(column => column.visible)
})

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    companyName: undefined,
    beginCreateTime: undefined,
    endCreateTime: undefined,
  },
})

const { queryParams } = toRefs(data)

/** 查询当事人信息列表 */
function getList() {
  loading.value = true
  if (null != daterangeCreateTime.value && '' != daterangeCreateTime.value) {
    queryParams.value.params = {}
    queryParams.value.params['beginCreateTime'] = daterangeCreateTime.value[0]
    queryParams.value.params['endCreateTime'] = daterangeCreateTime.value[1]
  } else {
    queryParams.value.params = {}
    queryParams.value.params['beginCreateTime'] = undefined
    queryParams.value.params['endCreateTime'] = undefined
  }
  getDataList(queryParams.value).then(response => {
    partyinfoList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeCreateTime.value = []
  proxy.resetForm('queryRef')
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  formId.value = undefined
  open.value = true
  title.value = '添加当事人信息'
  checkBtnType.value = 'add'
}

/** 修改按钮操作 */
function handleUpdate(row, type) {
  formId.value = row.id || ids.value
  open.value = true
  title.value = '修改当事人信息'
  checkBtnType.value = type
}

/**上传附件 */
const fileModal = ref(false)
const fileUploadList = ref([])
const rowId = ref('')
const handleUpload = async row => {
  rowId.value = row.id
  const res = await onSiteInspectionDetail(row.id)
  fileUploadList.value = res.data.ttsiteInspectionRecordFilesList || []
  fileModal.value = true
}
/** 预览 */
const previewList = ref([])
const preViewUrl = ref('')
const handleView = async row => {
  const res = await onSiteInspectionPreviewList({ id: row.id })
  previewList.value = res.data || []
}
const handlePreview = async val => {
  loading.value = true
  const { type, id } = previewList.value.find(item => item.id === val)
  const res = await onSiteInspectionPreview({
    type,
    id,
  })
  preViewUrl.value = res.msg
  if (!!preViewUrl.value) {
    window.open(preViewUrl.value)
  } else {
    ElMessage.warning('预览文件不存在')
  }
  loading.value = false
}
// 上传附件
const handleUploadConfirm = async () => {
  console.log('上传附件', fileUploadList.value)
  await onSiteInspectionUpload({ id: rowId.value, ttsiteInspectionRecordFilesList: fileUploadList.value })
  ElMessage.success('保存成功')
  fileModal.value = false
}

const handleSave = () => {
  getList()
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal
    .confirm(`是否确定删除 "${row.companyName}" 的现场检查记录？`)
    .then(function () {
      return onSiteInspectionDel(_ids)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}

/** 导出按钮操作 */
async function handleExport() {
  const _ids = ids.value
  const res = await onSiteInspectionExport(_ids)
  downloadBlob(res)
}

getList()
</script>

<style scoped lang="scss">
.dropdownView {
  font-size: var(--el-font-size-base);
  margin-top: 2px;
}
</style>
